<template>
  <view class="content">
    <NavbarCustom leftIcon="" bgColor="transparent" />
    <image :src="backgroundImage" mode="widthFix" class="background"></image>

    <view class="content-view">
      <scroll-view
        scroll-y
        style="height: 100%; width: 100%"
        @scrolltolower="reachBottom"
        scroll-anchoring
        enable-back-to-top
        refresher-default-style="white"
        :enable-flex="true"
      >
        <view class="head">
          <view class="title">
            <view class="title-text">
              {{ timeState }}{{ userInfo.nickname || "" }}
            </view>
            <view class="subtitle-text"> 欢迎来到E-Selina </view>
          </view>
          <view class="ai-button">
            <image :src="AIButtonImage" mode="" class="ai-button-icon"></image>
          </view>
        </view>
        <view class="hot">
          <view class="hot-background">
            <image
              :src="hotBackgroundImage"
              mode=""
              class="hot-background-image"
            >
            </image>
            <view class="title-view">
              <image :src="hotImage" mode="" class="title-icon"></image>
              <view class="title-text"> 热门推荐 </view>
            </view>
          </view>
          <view class="hot-content">
            <scroll-view
              scroll-x="true"
              scroll-anchoring
              :style="{ width: '100%', height: '100%' }"
            >
              <view class="hot-list">
                <HotCell
                  v-for="(item, index) in hotList"
                  :info="item"
                  :key="item.id"
                  :class="{
                    first: index === 0,
                    last: index === hotList.length - 1,
                  }"
                  @select="toDetail(item, index)"
                />
              </view>
            </scroll-view>
          </view>
        </view>
        <view class="collection">
          <view class="title-view">
            <image :src="collectionImage" mode="" class="title-icon"></image>
            <view class="title-text"> 我的收藏 </view>
          </view>
          <NoData v-if="noData" customStyle="margin-top: 0rpx;" />
          <view class="collection-content" v-else>
            <CollectionCell
              v-for="(item, index) in collectionList"
              :info="item"
              :key="item.id"
              @onCollection="clickCollection(item, index)"
              @select="toDetail(item, index)"
            />
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import NavbarCustom from "@/components/navbar-custom/index.vue";
import NoData from "@/components/no-data";
import HotCell from "./components/hot-cell.vue";
import CollectionCell from "./components/collection-cell.vue";
import { ref, onMounted, reactive, computed, nextTick } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";

import useUserStore from "@/store/user.js";
import { storeToRefs } from "pinia";
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore); // 响应式

import { getToken, checkToken } from "@/utils/common.js";
import { getRecommend, getFavorite } from "@/api/index/index.js";
import { addFavorite, removeFavorite } from "@/api/article";
const backgroundImage = ref("/static/images/index/background@3x.png");
const AIButtonImage = ref("/static/images/index/Mask-group@3x.png");
const hotBackgroundImage = ref("/static/images/index/Rectangle-203@3x.png");
const hotImage = ref("/static/images/index/redu@3x.png");
const collectionImage = ref("/static/images/index/wodeshoucang@3x.png");
const notification = ref("index-collection-list");

onLoad(() => {
  initPage();
  freshing.value = false;
  uni.$on(notification.value, () => {
    if (getToken()) {
      reloadList();
    } else {
      collectionList.value = [];
      loaded.value = true;
    }
  });
});
onUnload(() => {
  uni.$off([notification.value]);
});

const noData = computed(() => {
  return collectionList?.value?.length == 0 && loaded.value;
});

const initPage = () => {
  getHotList();
  if (getToken()) {
    reloadList();
  } else {
    collectionList.value = [];
    loaded.value = true;
  }
};

const hotList = ref([]);
const getHotList = async () => {
  try {
    let res = await getRecommend();
    hotList.value = res.data;
  } catch (e) {
    console.log(e);
    //TODO handle the exception
  }
};
const toDetail = (item) => {
  uni.$u.route({
    url: "/pages/article/article",
    params: {
      id: item.id,
    },
  });
};

const clickCollection = async (item) => {
  try {
    let res = null;
    let params = {
      articleId: item.id,
    };
    if (item.favorited === "1") {
      res = await removeFavorite(params);
    } else {
      res = await addFavorite(params);
    }
    if (res.code === 0) {
      item.favorited = item.favorited === "1" ? "0" : "1";
    }
  } catch (error) {
    console.log(error);
  }
};

const initInfo = () => {
  if (checkToken()) {
    getCollectionList();
  } else {
    setTimeout(() => {
      if (freshing.value) {
        triggered.value = false;
        freshing.value = false;
      }
    }, 1500);
  }
};
// 获取收藏列表
const collectionList = ref([]);
const triggered = ref(true);
const freshing = ref(false);
const loaded = ref(false);
const current = ref(1);
const size = ref(10);
const loadStatus = ref("loading");
const loading = ref(false);
const reloadList = () => {
  current.value = 1;
  loadStatus.value = "loading";
  getCollectionList();
};
const getCollectionList = async () => {
  if (current.value == 1) {
    collectionList.value = [];
    loaded.value = false;
  }
  let params = {
    offset: (current.value - 1) * size.value,
    limit: size.value,
  };
  try {
    let res = await getFavorite(params);
    let { data, info, count } = res;
    if (data) {
      data.map((e) => {
        e.favorited = "1";
      });
      collectionList.value.push(...data);
      // 更新底部加载状态
      console.log(collectionList.value.length);
      loadStatus.value =
        count > collectionList.value.length ? "loadmore" : "nomore";
    }
    setTimeout(() => {
      nextTick(() => {
        if (freshing.value) {
          triggered.value = false;
          freshing.value = false;
        }
      });
    }, 500);
  } catch (e) {
    console.log(e);
    nextTick(() => {
      if (freshing.value) {
        triggered.value = false;
        freshing.value = false;
      }
    });
    //TODO handle the exception
  }
  loaded.value = true;
};
// 滚动底部
const reachBottom = () => {
  console.log(loadStatus.value);
  if (loadStatus.value != "loadmore") return;
  current.value += 1;
  loadStatus.value = "loading";
  getCollectionList();
};
const onRefresh = () => {
  if (freshing.value) return;
  freshing.value = true;
  initInfo();
};
const onRestore = () => {
  triggered.value = "restore"; // 需要重置
};

const getTimeState = () => {
  // 获取当前时间
  let timeNow = new Date();
  // 获取当前小时
  let hours = timeNow.getHours();
  // 设置默认文字
  let state = ``;
  // 判断当前时间段
  if (hours >= 0 && hours <= 5) {
    state = `晚上好！`;
  } else if (hours > 5 && hours <= 10) {
    state = `早上好！`;
  } else if (hours > 10 && hours <= 14) {
    state = `中午好！`;
  } else if (hours > 14 && hours <= 18) {
    state = `下午好！`;
  } else if (hours > 18 && hours <= 24) {
    state = `晚上好！`;
  }
  return state;
};
const timeState = ref(getTimeState());
</script>

<style lang="scss" scoped>
.content {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  // background: linear-gradient(to bottom, #4bd5d9, #58dccc);

  .background {
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
  }

  .head {
    // top: -30rpx;
    // height: 136rpx;
    position: relative;
    z-index: 11;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    padding: 12rpx 32rpx 0 32rpx;
    margin-bottom: 40rpx;

    .title {
      color: #ffffff;

      .title-text {
        font-size: 48rpx;
        line-height: 48rpx;
        margin-bottom: 28rpx;
      }

      .subtitle-text {
        font-size: 48rpx;
        line-height: 48rpx;
      }
    }

    .ai-button {
      width: 78rpx;
      height: 78rpx;
      background: linear-gradient(360deg, #121452 0%, #3b9597 100%);
      border: 4rpx solid #ffffff;
      border-radius: 50%;

      .ai-button-icon {
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
      }
    }
  }

  .content-view {
    // margin-top: 100rpx;
    position: relative;
    z-index: 10;
    height: 100%;
    overflow: auto;
    padding-bottom: 128rpx;

    .title-view {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      padding: 0 32rpx;

      .title-icon {
        width: 38rpx;
        height: 38rpx;
        margin-right: 16rpx;
      }

      .title-text {
        font-size: 36rpx;
        line-height: 36rpx;
      }
    }

    .hot {
      .title-view {
        position: absolute;
        z-index: 10;
        left: 0;
        top: 0;
      }

      // margin-top: 10rpx;
      .hot-background {
        position: relative;
        height: 110rpx;
        margin-bottom: -2rpx;

        .hot-background-image {
          width: 100%;
          height: 100%;
        }
      }

      .hot-content {
        background: #ffffff;
        height: 300rpx;

        .hot-list {
          // display: block;
          // overflow-x: auto;
          // width: auto;
          display: flex;
          flex-wrap: nowrap;
          // overflow: hidden;
          // height: 300rpx;
          vertical-align: top;
          white-space: nowrap;
          // padding: 0 0rpx 0 12rpx;
          // line-height: 300rpx;
        }

        .first {
          margin-left: 12rpx;
          // line-height: 300rpx;
        }

        .last {
          margin-right: 32rpx;
        }
      }
    }

    .collection {
      padding-top: 70rpx;
      background-color: #ffffff;
    }

    .collection-content {
      padding: 0 32rpx;
      padding-bottom: 32rpx;
    }
  }
}
</style>
